package com.ef.web.action;

import java.util.List;

import com.ef.constant.ConfirmMessage;
import com.ef.domain.Menu;
import com.ef.service.MenuService;

public class MenuAction extends BaseAction<Menu> {

	private static final long serialVersionUID = 1L;
	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(MenuAction.class);
	private MenuService menuService;
	
	private List<Menu> menus;

	public String list() {
		
		menus = menuService.findAll();
		String treeData = "";
		for(Menu menu:menus){
			treeData+="d.add("+menu.getId()+","+replace(menu.getParent())+",'"+menu.getName()+"','javascript:view("+menu.getId()+", \\'"+menu.getName()+"\\', \\'"+menu.getLevel()+"\\')');\n ";
		}
		getRequest().setAttribute("treeData", treeData);
		return LIST;
	}
	
	private String replace(Menu parent){
		if(parent!=null)
			return parent.getId().toString();
		else 
			return "0";
	}

	public String save() {

		Menu menu = this.getModel();
		if(menu.getParent()!=null){
		if(menu.getParent().getId()==null){
			menu.setParent(null);
		}
		}
		menuService.saveOrUpdate(menu);
		this.setResult(ConfirmMessage.Menu);
		return EDIT;
	}
	public String edit(){
		return EDIT;
	}

	public MenuService getMenuService() {
		return menuService;
	}
	
	public String delete(){
		String id = getRequest().getParameter("id");
		menuService.delete(menuService.findById(Long.valueOf(id)));
		return NONE;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public List<Menu> getMenus() {
		return menus;
	}

	public void setMenus(List<Menu> menus) {
		this.menus = menus;
	}

}
